package egovframework.nanum.portal.home.service;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import egovframework.nanum.portal.util.AbcConfig;

@Service
public class HomeService {
	
	@Autowired
	private AbcConfig abcConfig;

	/************** NUNUM TEMP CODE START ***************/

	public HashMap checkUser(HttpServletRequest request, HttpServletResponse response) {
		String strResult = "";
		String strUserId = request.getParameter("userId");
		String strPassword = request.getParameter("password");
		String lang = request.getParameter("lang_cd");
		String useErrLimit = this.abcConfig.getProperty("login.password.error.limit.use");
		String strLimitCnt = this.abcConfig.getProperty("login.password.error.limit.cnt");
		String useOrderLogin = this.abcConfig.getProperty("login.check.orderDevice.use");
		if(useOrderLogin ==null){
			useOrderLogin = "N";
		}
		
		if(useErrLimit == null){
			useErrLimit = "N";			
		}
		if(strLimitCnt == null || strLimitCnt.equals("")){
			strLimitCnt = "5";
		}
		int limitCnt = Integer.parseInt(strLimitCnt);
		if( strUserId == null || strUserId.equals("") ) {
			strUserId = "";
		}
		if( strPassword == null || strPassword.equals("") ) {
			strPassword = "";
		}
		
		// 2013-09-27 apply nanum ecryption by 100c
		
		//logger.debug("password:" + strPassword);
		
//		String encPassword = XFCrypt.crypt(this.abcConfig.getProperty("password.enckey"), strPassword);
		String encPassword = this.commonUtil.cryptPassword(strPassword);
		
		//logger.debug("password encrypt:" + encPassword);
		
		UsrInfo ui = new UsrInfo();
		ui.setLogin_id(strUserId);
		ui.setUsr_pwd(encPassword);
		
		
		ui = this.usrInfoRepository.checkLogin(ui);
		
		Long duty_seq = Long.valueOf(-1);
		if ( ui != null && ui.getUsr_key() != null ) {
			
			
			UsrInfo tempUsr = new UsrInfo();
			tempUsr.setLogin_id(strUserId);
			tempUsr = this.usrInfoRepository.read(tempUsr);
			
			//비밀번호 애러 제한 건수옵션 사용할경우 
			if(useErrLimit.equals("Y")){
				//애러 제한보다 많이 페스워드를 틀렸을경우 로그인을 제한한다.
				if(tempUsr.getErr_cnt() >= limitCnt){
					HashMap hm2 = new HashMap();					
					hm2.put("strResult", "errPw");					
					return hm2;
				}else{
					//애러 제한보다 적은상태에서 로그인인징되었을경우 페스워드 에러건수를 항상 리셋해준다.
					this.usrInfoRepository.resetPWErrCnt(tempUsr.getUsr_key());
				}				
			}
			
			
			if(lang == null || lang.equals("")){
				lang = "ko";
			}
			tempUsr.setLang_cd(lang);
			
			
			if(useOrderLogin.equals("Y")){
				HashMap param = new HashMap();
				param.put("usr_id", tempUsr.getLogin_id());
				CmnCnnctLog cmnCnnctLog = this.cmnCnnctLogRepository.findLoginInfo(param);
				CmnCnnctLog cmnCnnctLogOut = this.cmnCnnctLogRepository.findLogOutInfo(param);
				boolean validLogin = false;				
				//로그인 정보가있을경우				
				if(cmnCnnctLog != null && cmnCnnctLog.getCnnct_ip() != null) {
					String loginIp = this.commonUtil.getAddressFromRequest(request);
					if(cmnCnnctLogOut != null && cmnCnnctLogOut.getCnnct_ip() != null){
						if(!cmnCnnctLog.getCnnct_ip().equals(cmnCnnctLogOut.getCnnct_ip())){
							HashMap errHm = new HashMap();
							errHm.put("strUserId", strUserId);
							errHm.put("preLoginInfo", cmnCnnctLog);
							errHm.put("strResult", "unvalidLogin");
							return errHm;
						}
					}else{
						if(!cmnCnnctLog.getCnnct_ip().equals(loginIp)){
							HashMap errHm = new HashMap();
							errHm.put("strUserId", strUserId);
							errHm.put("preLoginInfo", cmnCnnctLog);
							errHm.put("strResult", "unvalidLogin");
							return errHm;
						}
					}
					
					
				}				
			}
			
			
			this.usrInfoRepository.update(tempUsr);
			duty_seq = tempUsr.getDuty_seq();
			
			strResult = "success";
		} else {		
			
			//비밀번호 애러 제한 건수옵션 사용할경우
			if(useErrLimit.equals("Y")){			
				UsrInfo tempUsr = new UsrInfo();				
				tempUsr.setLogin_id(strUserId);
				tempUsr = this.usrInfoRepository.read(tempUsr);			
				if(tempUsr != null){				
					int errCnt = this.usrInfoRepository.findUsrPWErrCnt(tempUsr.getUsr_key());				
					if(errCnt >= limitCnt){
						strResult = "errPw";
					}else{
						strResult = "fail";
						this.usrInfoRepository.updatePWErrCnt(tempUsr.getUsr_key());
					}								
				}else{
					strResult = "fail";
				}
			}else{
				strResult = "fail";
			}			
		}

		//logger.debug("#################### userId : " + strUserId + " / pwd : " + strPassword + " / strResult : " + strResult);
		HashMap hm = new HashMap();
		hm.put("strUserId", strUserId);
		hm.put("strResult", strResult);
		hm.put("duty_seq", String.valueOf(duty_seq));
		return hm;
	}

}
